import os

import cv2
from ultralytics import YOLO
from PIL import Image, ImageTk


class video_way:

    def __init__(self):
        current_path = os.getcwd()
        model_file_path = os.path.join(current_path, "models", "yolov8n.pt")
        self.model = YOLO(model_file_path)

    def tkImage(self):
        # 创建视频捕获对象，读取笔记本电脑的本地摄像头流
        cap = cv2.VideoCapture(0)  # 使用本地摄像头，通常索引为0
        if not cap.isOpened():
            print(f"无法打开视频文件：{0}")
            return
        ref, frame = cap.read()
        if not ref:
            print("Failed to capture frame")
            return None
        results = self.model.predict(frame, device="cpu", conf=float(65) / 100.0)
        # frame = cv2.flip(frame, 1)  # 摄像头翻转
        cvimage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        pilImage = Image.fromarray(cvimage)
        pilImage = pilImage.resize((800, 600), Image.LANCZOS)
        tkImage = ImageTk.PhotoImage(image=pilImage)
        return tkImage


